<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\goods;

use app\adminapi\controller\Base;
use app\common\model\GoodsSpec;
use app\service\goods\CategoryService;
use app\common\model\GoodsCategory as GoodsCategoryModel;

class Category extends Base
{
    /**
     * Category list
     * @auth true
     */
    public function list()
    {
        $service = new CategoryService();
        // Return tree structure
        $list = $service->getCategoryTreeWithGoods();

        $this->success('', [
            'list'  => $list,
            'total' => count($list)
        ]);
    }

    /**
     * Get navigation menu categories
     */
    public function menuList()
    {
        $list = GoodsCategoryModel::getMenuCategories();
        $this->success('', $list);
    }

    /**
     * Category details
     */
    public function detail()
    {
        $id      = inputs('id/d', 0);
        $service = new CategoryService();
        $detail  = $service->getCategoryDetail($id);

        $this->success('', $detail);
    }

    /**
     * Add category
     */
    public function add()
    {
        $post = [
            'pid'             => inputs('pid/d', 0),
            'name'            => inputs('name', ''),
            'pic'             => inputs('pic/s', ''),
            'sort'            => inputs('sort/d', 0),
            'status'          => inputs('status/d', 1),
            'is_menu'         => inputs('is_menu/d', 0),
            'spec_id'         => inputs('spec_id/d', 0),
            'is_spec_filter'  => inputs('is_spec_filter/d', 0),
            'search_filters'  => inputs('search_filters/a', []),
            'seo_title'       => inputs('seo_title/s', ''),
            'seo_keywords'    => inputs('seo_keywords/s', ''),
            'seo_description' => inputs('seo_description/s', ''),
            'template'        => inputs('template/s', ''),
        ];

        if (empty($post['name'])) {
            $this->error(trans('category_name_required'));
        }

        $service = new CategoryService();

        // Check if it's batch add (multi-line text)
        if (strpos($post['name'], "\n") !== false || strpos($post['name'], "\r") !== false) {
            // Split names by line breaks
            $nameArray = preg_split('/\r\n|\r|\n/', $post['name']);
            $nameArray = array_filter(array_map('trim', $nameArray)); // Remove empty lines and trim spaces

            if (empty($nameArray)) {
                $this->error(trans('category_name_required'));
            }

            // Count results
            $successCount = 0;
            $failCount    = 0;

            // Loop to add each category
            foreach ($nameArray as $name) {
                if (empty($name)) {
                    continue;
                }

                try {
                    $categoryData         = $post;
                    $categoryData['name'] = $name;
                    $service->saveCategory($categoryData);
                    $successCount++;
                } catch (\Exception $e) {
                    $failCount++;
                }
            }

            $this->success(trans('batch_add_completed', ['%success%' => $successCount, '%fail%' => $failCount], 'goods_category'));
        } else {
            // Single add
            $service->saveCategory($post);
            $this->success();
        }
    }

    /**
     * Edit category
     */
    public function edit()
    {
        $post = [
            'id'              => inputs('id/d', 0),
            'pid'             => inputs('pid/d', 0),
            'name'            => inputs('name/s', ''),
            'pic'             => inputs('pic/s', ''),
            'sort'            => inputs('sort/d', 0),
            'status'          => inputs('status/d', 1),
            'is_menu'         => inputs('is_menu/d', 0),
            'spec_id'         => inputs('spec_id/d', 0),
            'is_spec_filter'  => inputs('is_spec_filter/d', 0),
            'search_filters'  => inputs('search_filters/a', []),
            'seo_title'       => inputs('seo_title/s', ''),
            'seo_keywords'    => inputs('seo_keywords/s', ''),
            'seo_description' => inputs('seo_description/s', ''),
            'template'        => inputs('template/s', ''),
        ];

        if (empty($post['name'])) {
            $this->error(trans('category_name_required'));
        }

        $service = new CategoryService();
        $service->saveCategory($post);

        $this->success();
    }

    /**
     * Delete category
     */
    public function del()
    {
        $id = inputs('id/d', 0);

        $service = new CategoryService();
        $service->deleteCategory($id);

        $this->success();
    }

    /**
     * Get category associated spec filter fields
     */
    public function getSpecFilter()
    {
        $cate_id = inputs('cate_id/d', 0);
        if (empty($cate_id)) {
            $this->error(trans('category_id_required'));
        }

        $service = new CategoryService();
        $fields  = $service->getCategorySpecFilter($cate_id);

        $this->success('', $fields);
    }

    /**
     * Get spec options (for category spec association selection)
     */
    public function getSpecOptions()
    {
        $list = GoodsSpec::where('status', 1)
            ->field('id, name')
            ->order('sort desc, id desc')
            ->select();

        $this->success('', $list);
    }

    /**
     * Get category tree structure
     */
    public function getCategoryTree()
    {
        $service = new CategoryService();
        $tree    = $service->getCategoryTree();

        $this->success('', $tree);
    }

    /**
     * Update category status
     */
    public function status()
    {
        $id    = inputs('id/d', 0);
        $field = inputs('field/s', 'status');
        $value = inputs('value/d', 0);

        // Only allow modification of specific fields
        if (!in_array($field, ['status', 'sort', 'is_spec_filter'])) {
            $this->error(trans('field_not_allowed'));
        }

        $service = new CategoryService();
        $res     = $service->updateCategoryStatus($id, $field, $value);

        return $res ? $this->success() : $this->error();
    }

    /**
     * Toggle navigation menu status
     */
    public function toggleMenu()
    {
        $id = inputs('id/d', 0);

        $service = new CategoryService();
        $service->toggleCategoryMenu($id);

        $this->success();
    }

    /**
     * Get available template list for category pages
     */
    public function getTemplateList()
    {
        $service   = new CategoryService();
        $templates = $service->getCategoryTemplateList();

        $this->success('', $templates);
    }
}
